<template>
  <BaseMainSlot>
    <template v-slot:typenodeslot>
      <SelectButton
        :topitem-select-list="topitemSelectList"
        @topitemtype="topitemtype"
      />
    </template>
    <template v-slot:searchbox>
      <div class="seach-box">
        <div class="select-box-content">
          <div class="select-box-content-name">任务模板名称：</div>
          <el-input
            v-model="planTaskModelName"
            clearable
            placeholder="请输入任务模板名称"
            @change="queryPageList()"
          />
        </div>
        <div class="select-box-content">
          <div class="select-box-content-name">执行人：</div>
          <el-select
            clearable
            v-model="personNo"
            placeholder="请选择"
            @change="queryPageList()"
          >
            <el-option
              v-for="item in mixUserList"
              :key="item.personNo"
              :label="item.username"
              :value="item.personNo"
            ></el-option>
          </el-select>
        </div>
      </div>
    </template>
    <template v-slot:btnsBar>
      <ActionBar
        v-if="topitemtypeId==='使用中'"
        :add-active="addActive"
        :del-active="delActive"
        :page-no="156"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:content>
      <e-table
        ref="tableData"
        rowKey="planTaskModelId"
        :table-data="tableData"
        :table-columns="tableLabel"
        :page="currentPage"
        :size="pageSize"
        :total="totalSize"
        :loading="loading"
        :table-option="tableOption"
        :table-column-sum="topitemtypeId"
        @sizeChange="changePageSize"
        @pageChange="changeCurrentPage"
        @tableUpdatePlus="mixTableUpdatePlus"
        @handleSelectionChange="handleSelectionChange"
      >
        <template
          slot="equipment"
          slot-scope="scoped"
          v-if="scoped.row.planTaskModelId"
        >
          <span
            class="table-btns-box"
            @click="mixQueryInspectionPlanTaskModel(scoped.row.planTaskModelId)"
          >
            <i class="el-icon-view"></i>
            <span>点击查看</span>
          </span>
        </template>
        <template
          v-if="scoped.row.planTaskModelId"
          slot="generateHour"
          slot-scope="scoped"
        >{{ mixChangeGenerateHour(scoped.row.generateHour) }}</template>
        <template
          v-if="scoped.row.planTaskModelId"
          slot="intervalPeriod"
          slot-scope="scoped"
        >{{ scoped.row.intervalPeriod }}天</template>
        <template
          v-if="scoped.row.planTaskModelId"
          slot="performStartTime"
          slot-scope="scoped"
        >{{ mixChangePerformTime(scoped.row) }}</template>
        <template slot="startTime" slot-scope="scoped">
          <span>
            {{ scoped.row.startTime?scoped.row.startTime:'' }}
            <span
              v-if="scoped.row.startTime&&scoped.row.endTime"
            >至</span>
            {{ scoped.row.endTime?scoped.row.endTime:'' }}
          </span>
        </template>
        <template
          slot="status"
          slot-scope="scoped"
          v-if="scoped.row.planTaskModelId"
        >
          <el-switch
            style="margin-right:5px"
            v-if="((topitemtypeId==='使用中'&&judgePermission(151,'stop'))||(topitemtypeId==='暂停中'&&judgePermission(151,'start')))"
            v-model="scoped.row.operate_status"
            active-color="#64D9D6"
            inactive-color="#9E9E9E"
            @change="changeStatus(scoped.row)"
          ></el-switch>
        </template>
        <template
          slot="operate"
          v-if="scoped.row.planTaskModelId"
          slot-scope="scoped"
        >
          <span
            v-if="judgePermission(151,'edit')"
            class="table-btns-box"
            @click="edit(scoped.row)"
          >
            <i class="el-icon-edit-outline"></i>
            <span>修改</span>
          </span>
          <span
            v-if="judgePermission(151,'deleteone')"
            class="table-btns-box table_del_btn"
            @click="delOne(scoped.row)"
          >
            <i class="el-icon-delete"></i>
            <span>删除</span>
          </span>
        </template>
      </e-table>

      <AddEditDialog
        ref="addEditDialog"
        :now-chance-stau="nowChanceStau"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <SeeEquip
        :is-show-equip="isShowEquip"
        :equip-data="showCheckList"
        @closeDialog="isShowEquip = false"
      />
      <MessageDialog
        ref="MessageDialog"
        :show.sync="showChangeStatusDialog"
        :message="messageTitle"
        :edit-object="editObject"
        :title-text="titleText"
        @save="save"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import SeeEquip from "@/components/seeEquip/index.vue";
import ActionBar from "@/components/ActionBar";
import inspectionTaskTemplateApi from "@/api/equip-inspection/inspection-task-template";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import { mymixin } from "@/utils/mixin";
import { maintenanceMixins } from "@/utils/maintenance-mixins";
import SelectButton from "@/components/equipTypeSelectButton/selcetButton.vue";
import MessageDialog from "@/components/detailDialog/message-dialog.vue";
import { mapGetters } from "vuex";
export default {
  name: "InspectionTaskTemplate",
  components: {
    BaseMainSlot,
    AddEditDialog,
    SelectButton,
    ActionBar,
    MessageDialog,
    SeeEquip,
  },
  mixins: [mymixin, maintenanceMixins],
  data() {
    return {
      startTime: [],
      //  搜索条件:设备名称：
      equipmentCode: "",
      equipmentArr: [],
      //  搜索条件:执行人
      personNo: "",
      equipmentList: [], //设施列表
      // 搜索条件:任务模板名称
      planTaskModelName: "",
      // 搜索条件:任务模板名称
      planTaskName: "",
      // 使用中,暂停中,已失效,未启用
      topitemtypeId: "",
      // 暂停恢复
      showChangeStatusDialog: false,
      messageTitle: "",
      loading: false,
      topitemSelectList: [
        { id: "使用中", name: "使用中" },
        { id: "暂停中", name: "暂停中" },
        { id: "已失效", name: "已失效" },
        { id: "未启用", name: "未启用" },
      ],

      // 表单展示项
      tableLabel: [
        {
          label: "任务模板名称",
          param: "planTaskModelName",
          show: true,
        },
        {
          label: "关联设备",
          param: "equipment",
          show: true,
          slotName: "equipment",
          notSearch: true,
        },
        {
          label: "所属计划",
          param: "planTaskModelName",
          show: true,
          notSearch: true,
        },
        {
          label: "任务间隔时间",
          param: "intervalPeriod",
          show: true,
          notSearch: true,
          slotName: "intervalPeriod",
        },
        {
          label: "重复次数",
          param: "generateNum",
          show: true,
          notSearch: true,
          width: 80,
        },
        {
          label: "任务生成时间",
          param: "generateHour",
          show: true,
          type: "datetime",
          slotName: "generateHour",
        },
        {
          label: "任务有效时间",
          param: "startTime",
          show: true,
          type: "datetime_range",
          slotName: "startTime",
          width: 200,
        },
        {
          label: "执行人",
          param: "userName",
          show: true,
        },
        {
          label: "任务执行时间",
          param: "performStartTime",
          show: true,
          slotName: "performStartTime",
          notSearch: true,
        },
        {
          label: "是否启用",
          param: "status",
          show: true,
          slotName: "status",
          notSearch: true,
        },
      ],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
      showCheckList: [],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    this.mixQueryInspectionHaveCheckList();
    this.mixQueryUserList();
  },
  mounted() {},
  methods: {
    // 使用中,暂停中,已失效,未启用
    topitemtype(e) {
      this.topitemtypeId = e;
      // 获取表格数据
      this.queryPageList();
    },
    queryPageList(e) {
      this.loading = true;
      // 获取数据
      let params = {
        page: this.currentPage,
        size: this.pageSize,
      };
      if (this.topitemtypeId === "使用中") {
        params["status"] = 1;
        params["pastDue"] = 1;
      }
      if (this.topitemtypeId === "暂停中") {
        params["status"] = 0;
        params["pastDue"] = 1;
      }
      if (this.topitemtypeId === "已失效") {
        params["pastDue"] = 3;
      }
      if (this.topitemtypeId === "未启用") {
        params["pastDue"] = 2;
      }
      if (this.planTaskModelName || e?.planTaskModelName) {
        params["planTaskModelName"] =
          this.planTaskModelName || e?.planTaskModelName;
      }
      if (this.personNo || e?.personNo) {
        params["personNo"] = this.personNo || e?.personNo;
      }
      inspectionTaskTemplateApi.queryPageList(params).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || {};
          this.totalSize = data.total;
          data.list.forEach((item) => {
            item["operate_status"] = item.status;
          });
          this.tableData = data.list;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      if (list.length == 0) {
        this.delActive = false;
        return;
      }
      this.checkedIdList = [];
      let emptyList = [];
      list.forEach((item) => {
        if (item.planTaskModelId) {
          this.checkedIdList.push(item.planTaskModelId);
        } else {
          emptyList.push(item);
        }
      });
      if (this.checkedIdList.length >= 1) {
        this.delActive = true;
      } else {
        this.delActive = false;
        this.$message.warning("不可选择空数据！");
      }
      if (list.length === emptyList.length) {
        this.toggleNoSelection();
      } else {
        this.toggleNoSelection(emptyList);
      }
    },
    // 单个删除
    delOne(data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          inspectionTaskTemplateApi
            .delList({ planTaskModelIdList: [data.planTaskModelId] })
            .then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.queryPageList();
                this.resetActionBar();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 表格删除
    delmessage() {
      inspectionTaskTemplateApi
        .delList({ planTaskModelIdList: this.checkedIdList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.queryPageList();
            this.resetActionBar();
          }
        });
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true;
    },
    // 修改
    edit(row) {
      if (row.planTaskModelId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true;
      } else {
        this.editObject = {};
      }
    },
    //状态变更,点击的时候，list里的operate_status状态已经改变，需要通过status改变成之前的状态
    changeStatus(data) {
      if (data.status === true) {
        this.stop(data);
      } else {
        this.start(data);
      }
    },
    // 启用计划
    start(row) {
      this.editObject = JSON.parse(JSON.stringify(row));
      this.titleText = "模板恢复";
      this.messageTitle = "确认恢复模板？";
      this.showChangeStatusDialog = true;
      this.resetSwitchStatus(row);
    },
    // 停用计划
    stop(row) {
      this.editObject = JSON.parse(JSON.stringify(row));
      this.titleText = "模板停用";
      this.messageTitle = "确认停用模板？";
      this.showChangeStatusDialog = true;
      this.resetSwitchStatus(row);
    },
    //状态变更,点击的时候，list里的operate_status状态已经改变，需要通过status改变成之前的状态
    resetSwitchStatus(data) {
      this.tableData.forEach((item) => {
        if (item.equipmentCode === data.equipmentCode) {
          item.operate_status = item.status;
          console.log("start11", item);
        }
      });
    },
    // 启停计划
    save(data) {
      var params = {};
      if (this.messageTitle === "确认恢复模板？") {
        params = { planTaskModelId: data["planTaskModelId"], status: true };
      }
      if (this.messageTitle === "确认停用模板？") {
        params = { planTaskModelId: data["planTaskModelId"], status: false };
      }
      inspectionTaskTemplateApi.edit(params).then((res) => {
        if (res.code === 1) {
          this.queryPageList();
          this.closeDialog();
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    closeDialog() {
      this.showAddEditDialog = false;
      this.showChangeStatusDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
      this.queryPageList();
    },
    cancel() {
      this.showAddEditDialog = false;
      this.showChangeStatusDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
